<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
    <template #insertFooter>
      <a-button type="primary" danger @click="handleTest"> {{ t('测试链接') }} </a-button>
    </template>
  </BasicModal>
</template>
<script lang="tsx" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { FormSchema } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import {
    addDatabaseLink,
    getDatabaseLink,
    updateDatabaseLink,
    testDatabaseLink,
  } from '/@/api/system/databaselink';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const accountFormSchema: FormSchema[] = [
    {
      field: 'dbName',
      label: t('数据库名称'),
      component: 'Input',
      required: true,
      colProps: { span: 24 },
    },
    {
      field: 'dbType',
      label: t('数据库类型'),
      component: 'Select',
      required: true,
      componentProps: {
        options: [
          { label: 'mysql', value: 'mysql' },
          { label: 'sqlserver', value: 'sqlserver' },
          { label: 'oracle', value: 'oracle' },
          { label: 'pgsql', value: 'pgsql' },
          { label: 'dm', value: 'dm' },
          { label: 'mariadb', value: 'mariadb' },
          { label: 'sqlite', value: 'sqlite' },
          { label: 'gbase', value: 'gbase' },
          { label: 'oceanbase', value: 'oceanbase' },
          { label: 'h2', value: 'h2' },
        ],
      },
      colProps: { span: 24 },
    },
    {
      field: 'dbVersion',
      label: t('数据库版本'),
      component: 'Input',
      colProps: { span: 24 },
    },
    {
      field: 'host',
      label: t('链接'),
      required: true,
      component: 'InputTextArea',
      colProps: { span: 24 },
    },
    {
      field: 'username',
      label: t('账号'),
      component: 'Input',
      required: true,
      colProps: { span: 24 },
    },
    {
      field: 'password',
      label: t('密码'),
      component: 'InputPassword',
      componentProps: {
        visibilityToggle: true,
      },
      required: true,
      colProps: { span: 24 },
    },
  ];

  const emit = defineEmits(['success', 'register']);

  const { notification } = useMessage();
  const isUpdate = ref(true);
  const rowId = ref('');
  const loading = ref(false);

  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    labelWidth: 100,
    schemas: accountFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });

    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      rowId.value = data.id;
      console.log(rowId.value);
      const record = await getDatabaseLink(data.id);

      setFieldsValue({
        ...record,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? t('新增数据库链接') : t('编辑数据库链接')));

  const handleTest = async () => {
    const values = await validate();
    console.log('handleTest');

    const ok = await testDatabaseLink(values);
    loading.value = true;
    if (!ok) {
      notification.error({
        message: t('提示'),
        type: 'warning',
        description: t('未能连接上数据库'),
      }); //提示消息
    } else {
      notification.success({
        message: t('提示'),
        description: t('成功'),
      }); //提示消息
    }
    loading.value = false;
  };

  async function handleSubmit() {
    try {
      const values = await validate();

      setModalProps({ confirmLoading: true });
      // TODO custom api
      if (!unref(isUpdate)) {
        //false 新增
        await addDatabaseLink(values);
        notification.success({
          message: t('提示'),
          description: t('数据库连接新增成功！'),
        }); //提示消息
      } else {
        values.id = unref(rowId);
        await updateDatabaseLink(values);
        notification.success({
          message: t('提示'),
          description: t('数据库连接修改成功！'),
        }); //提示消息
      }
      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
